<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/8 0008
 * Time: 上午 9:28
 */

namespace Qgs\Controller;


use Think\Page;

class GoodsPromotionController extends BaseController
{

    public $local_id;
    public function __construct()
    {
        parent::__construct();
        $this->local_id = session('userInfo')['local_id'];
    }


    /**
     * 商品促销列表
     */

    public function index()
    {
        $time = time();
        $num = I('num',5);
        $type = I('type');
        if ($type =='timeout') {
            $where['end_time']=['LT',$time];
        }else{
            $where['end_time']=['EGT',$time];
        }
        $where['local_id'] = $this->local_id;
        // 排序
        $order = I('param.order', 'desc');
        $order == 'asc' ? 'desc' : 'asc';
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign(['order' => $sunxu]);
        $order = ['id' => $order];

        $storegoods =M('b2c_store_goods_promotion');
        $count =$storegoods->where($where)->count();

        $Page = new \Think\Page($count, $num);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $promotion_msg = $storegoods->where($where)->order($order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        foreach($promotion_msg as &$v){
            $v['type_question_msg']=$this->type_question($v['type_question']);
            $v['type_result_msg']=$this->type_result($v['type_result']);
            $v['time_type']=$this->time($v['end_time'],$v['start_time']);

        }


        $this->assign([
            'msg'  => $promotion_msg,
            'show' => $show
        ]);
        $this->display();

    }

    public function type_question($type_question)
    {
        switch($type_question){
            case 1:
                $re = '指定商品';
                break;
        }
        return $re;
    }
    public function type_result($type_result)
    {
        switch($type_result){
            case 1:
                $cx = '自定义促销价';
                break;
            case 2:
                $cx = '减去固定价格';
                break;
        }
        return $cx;
    }
    public function time($endtime,$starttime)
    {
        $time=time();
        if ($starttime>$time) {
            $res = '活动还未开始';
        }
        if ($endtime>$time && $time>$starttime) {
            $res = '活动进行中';
        }
        if ($endtime<=$time) {
            $res = '活动已结束';
        }
        return $res;
    }
    /*
     * 添加商品促销
     */
    public function add()
    {
        if (!IS_POST) {
            $this->display('add');
        }else{


            $name = I('name'); // 促销  规则名称
            $description =I('description'); // 描述
            $display = I('display'); // 启用状态
            $sort = I('sort') ; // 排序
            $type_question = I('type_question'); //促销条件
            $store_id  = I('goods_id');  // 商品id
            $current_price  = I('current_price');  // 售价
            $promotion_price = I('promotion_price'); // 自定义商品促销的价格 数组
            $type_result = I('type_result'); // 促销结果类型 1为 自定义促销价格  2为 指定商品减去对应价格
            $result_price = I('result_price'); // 指定商品价格减去对应价格
            $start_time = I("start_time");
            $end_time = I("end_time");
            $resultprices = number_format($result_price,2);
            $price_s=[];
            foreach($promotion_price as $v){
                $price_s[] =number_format($v,2);

            }
            if (strtotime($start_time) >= strtotime($end_time)) {
                $this->error('开始时间不能大于结束时间');
            }
            if ($store_id==null ) {
                $this->error('商品不能为空');
            }
            $data['name']=$name;
            $data['local_id'] =  $this->local_id;
            $data['description'] = $description;
            $data['display'] = $display;
            $data['sort']=$sort;
            $data['type_question'] =$type_question;
            $data['type_result'] = $type_result;
            $data['start_time'] = strtotime($start_time);
            $data['end_time'] = strtotime($end_time);
            $data['create_time'] = time();
            $data['guding'] =$result_price;


            if ($type_question ==1) {
                if ($type_result == 1){
                    $current_p = array_combine($current_price,$price_s);
                    foreach($current_p as $k=>$v)
                    {
                        if($v>=$k){
                            $this->error('促销价不能大于等于售价!');exit;
                        }

                    }
                    $storeID_promotion = array_combine($store_id,$price_s);
                    $store_promotion =json_encode($storeID_promotion);
                }

                if ($type_result == 2) {
                    foreach($current_price as $v){
                        if($resultprices>=$v){
                            $this->error('减去固定价不能大于售价!');exit;
                        }
                    }
                    if($resultprices<=0.00){
                        $this->error('减去固定价最低为0.01');exit;
                    }

                    $price_s=[];
                    $current=[];
                    for($i = 1 ;$i<=count($store_id);$i++){
                        $price_s[] =number_format($result_price,2);

                    }
                    foreach($current_price as $v){
                        $current[]=$v-$result_price;
                    }
                    $storeID_promotion = array_combine($store_id,$current);
                    $store_promotion =json_encode($storeID_promotion);
                }

                $data['store_promotion']=$store_promotion;
            }


            $activity_product=[];
            foreach($store_id as $k){
                $activity_product[]=[
                    'local_id'=>$this->local_id,
                    'store_id'=>$k,
                    'start_time'=>strtotime($start_time),
                    'end_time'=>strtotime($end_time),
                    'type'=>3,

                ];
            }
            $endtime =time();
            $where['end_time']=['elt',$endtime];
            $where['local_id']=$this->local_id;
            $where['type']=3;
            $e = M('store_activity_product')->where($where)->delete();
            $e = M('store_activity_product')->addAll($activity_product);
            $result = M('b2c_store_goods_promotion')->add($data);

//            $goods_data=array();
//            $goods_prices =array_combine($store_id,$current_price);
//            $goods_price =array_combine($store_id,$promotion_price);
//            if ($type_result ==1) {
//                foreach($goods_price as $k=>$v)
//                {
//                    $goods_data[]=[
//                    'name'=>$name,
//                    'local_id' =>  $this->local_id,
//                    'description' => $description,
//                    'display'=> $display,
//                    'sort'=>$sort,
//                    'type_question' =>$type_question,
//                    'type_result'=> $type_result,
//                    'start_time'=> strtotime($start_time),
//                    'end_time'=> strtotime($end_time),
//                    'create_time' => time(),
//                    'store_id'=>$k,
//                    'promotion_price'=>number_format($v,2),
//                    'after_price'=>number_format($v,2)
//                    ];
//                }
//            }
//            if ($type_result ==2) {
//                foreach($goods_prices as $k=>$v)
//                {
//
//                    $goods_data[]=[
//                        'name'=>$name,
//                        'local_id' =>  $this->local_id,
//                        'description' => $description,
//                        'display'=> $display,
//                        'sort'=>$sort,
//                        'type_question' =>$type_question,
//                        'type_result'=> $type_result,
//                        'start_time'=> strtotime($start_time),
//                        'end_time'=> strtotime($end_time),
//                        'create_time' => time(),
//                        'store_id'=>$k,
//                        'promotion_price'=>number_format($result_price,2),
//                        'after_price'=>number_format($v-$result_price,2)
//                    ];
//            }
//          }
//            $result = M('b2c_store_goods_promotion')->addAll($goods_data);
            if ($result) {
                $this->success('添加成功', U('index'));
            } else {
                $this->error('添加失败', U('index'));
            }
        }



    }



    /**
     * 单个开启显示或关闭显示
     */

    public function change()
    {
        if (!IS_AJAX) {
            $return = array(
                'status' => false,
                'message' => '非法请求',
            );
            $this->ajaxReturn($return);
        }
        $id = I('get.id');
        $status = I('get.status')=='true'?'1':'0';
        $result = M('b2c_store_goods_promotion')->where(['id'=>$id])->save(['display'=>$status]);
        if ($result !== false) {
            $this->ajaxReturn(['status'=>true, 'message'=>'成功', 'data'=>'']);
        } else {
            $this->ajaxReturn(['status'=>false, 'message'=>'失败', 'data'=>'']);
        }
    }




    /**
     * 修改数据
     */
    public function update()
    {

        $id = I('id');
        $goods_promotion = M('b2c_store_goods_promotion a');
        $time = time();
        $where['end_time'] = ['EGT', $time];
        $where['id'] = $id;
        $where['local_id'] = $this->local_id;
        $result = $goods_promotion->where($where)->find();
        $store_promotion= json_decode($result['store_promotion']);
        $store_promotion= $this->object_to_array($store_promotion);// 对象转数组
        $goods_idarray =array_keys($store_promotion); //取键名(store_id)
        $goods_idarray =implode(',',$goods_idarray); //将数组变为字符串
        $promotion_price = array_values($store_promotion);
        $products = M('b2c_store_product a')
            ->where(['a.store_pid' => ['in', $goods_idarray],'local_id'=> $this->local_id])
            ->order("field(a.store_pid,$goods_idarray)")
            ->select();

        for($i=0; $i<count($promotion_price); $i++){
            $products[$i]['promotion_price']=$promotion_price[$i];
            $products[$i]['promotion_price_guding']=$result['guding'];
        }

        $this->assign(['msg'=>$result,'goods'=>$products]);
        $this->display();
    }


    public function detai()
    {

        $id = I('id');
        $goods_promotion = M('b2c_store_goods_promotion a');
        $time = time();
        $where['end_time'] = ['EGT', $time];
        $where['id'] = $id;
        $where['local_id'] = $this->local_id;
        $result = $goods_promotion->where($where)->find();
        $store_promotion= json_decode($result['store_promotion']);
        $store_promotion= $this->object_to_array($store_promotion);// 对象转数组
        $goods_idarray =array_keys($store_promotion); //取键名(store_id)
        $goods_idarray =implode(',',$goods_idarray); //将数组变为字符串
        $promotion_price = array_values($store_promotion);
        $products = M('b2c_store_product a')
            ->where(['a.store_pid' => ['in', $goods_idarray],'local_id'=> $this->local_id])
            ->order("field(a.store_pid,$goods_idarray)")
            ->select();

        for($i=0; $i<count($promotion_price); $i++){
            $products[$i]['promotion_price']=$promotion_price[$i];
            $products[$i]['promotion_price_guding']=$result['guding'];
        }

        $this->assign(['msg'=>$result,'goods'=>$products]);
        $this->display('detai');
    }


    function object_to_array($obj) {
        $obj = (array)$obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array)object_to_array($v);
            }
        }

        return $obj;
    }

    public function save()
    {
        if (!IS_POST) {
            $this->display('add');
        } else {
            $id = I('id');
            $name = I('name'); // 促销  规则名称
            $description = I('description'); // 描述
            $display = I('display'); // 启用状态
            $sort = I('sort'); // 排序
            $type_question = I('type_question'); //促销条件
            $store_id = I('goods_id');  // 商品id
            $current_price = I('current_price');  // 售价
            $promotion_price = I('promotion_price'); // 自定义商品促销的价格 数组
            $type_result = I('type_result'); // 促销结果类型 1为 自定义促销价格  2为 指定商品减去对应价格
            $result_price = I('result_price'); // 指定商品价格减去对应价格
            $start_time = I("start_time");
            $end_time = I("end_time");
            $resultprices = number_format($result_price,2);
            $price_s=[];
            foreach($promotion_price as $v){
                $price_s[] =number_format($v,2);

            }
            if (strtotime($start_time) >= strtotime($end_time)) {
                $this->error('开始时间不能大于结束时间');
            }
            if ($store_id == null) {
                $this->error('不能为空', U('add'));
            }
            $data['id']=$id;
            $data['name'] = $name;
            $data['local_id'] = $this->local_id;
            $data['description'] = $description;
            $data['display'] = $display;
            $data['sort'] = $sort;
            $data['type_question'] = $type_question;
            $data['type_result'] = $type_result;
            $data['start_time'] = strtotime($start_time);
            $data['end_time'] = strtotime($end_time);
            $data['create_time'] = time();
            $data['guding'] =$result_price;
            if ($type_question ==1) {
                if ($type_result == 1){
                    $current_p = array_combine($current_price,$price_s);
                    foreach($current_p as $k=>$v)
                    {
                        if($v>=$k){
                            $this->error('促销价不能大于等于售价!');exit;
                        }

                    }
                    $storeID_promotion = array_combine($store_id,$price_s);
                    $store_promotion =json_encode($storeID_promotion);
                }

                if ($type_result == 2) {
                    foreach($current_price as $v){
                        if($resultprices>=$v){
                            $this->error('减去固定价不能大于售价!');exit;
                        }
                    }
                    if($resultprices<=0.00){
                        $this->error('减去固定价最低为0.01');exit;
                    }

                    $price_s=[];
                    $current=[];
                    for($i = 1 ;$i<=count($store_id);$i++){
                        $price_s[] =number_format($result_price,2);

                    }
                    foreach($current_price as $v){
                        $current[]=$v-$result_price;
                    }
                    $storeID_promotion = array_combine($store_id,$current);
                    $store_promotion =json_encode($storeID_promotion);
                }

                $data['store_promotion']=$store_promotion;
            }
            $promotion = M('b2c_store_goods_promotion');
            $where['id'] = $id;
            $where['local_id'] = $this->local_id;
            $discount_coupon_msg = $promotion->where($where)->find();
            $where1['end_time']=$discount_coupon_msg['end_time'];
            $where1['start_time']=$discount_coupon_msg['start_time'];
            $where1['local_id']=$this->local_id;
            $where1['type']=3;
             M('store_activity_product')->where($where1)->delete();
            $activity_product=[];
            foreach($store_id as $k){
                $activity_product[]=[
                    'local_id'=>$this->local_id,
                    'store_id'=>$k,
                    'start_time'=>strtotime($start_time),
                    'end_time'=>strtotime($end_time),
                    'type'=>3,

                ];
            }
           M('store_activity_product')->addAll($activity_product);

            $result = M('b2c_store_goods_promotion')->save($data);
            if ($result) {
                $this->success('修改成功', U('index'));
            } else {
                $this->error('修改失败', U('index'));
            }
        }

    }


    /**
     * 删除
     */

    public function delete(){
        $id = I('id');
        $promotion = M('b2c_store_goods_promotion');
        $where['id'] = $id;
        $where['local_id'] = $this->local_id;
        $discount_coupon_msg = $promotion->where($where)->find();
        $where1['end_time']=$discount_coupon_msg['end_time'];
        $where1['start_time']=$discount_coupon_msg['start_time'];
        $where1['local_id']=$this->local_id;
        $where1['type']=3;
        $e = M('store_activity_product')->where($where1)->delete();
        $result = M('b2c_store_goods_promotion')->delete($id);
        if ($result) {
            $this->success('删除成功', U('index'));
        } else {
            $this->error('删除失败', U('index'));
        }
    }


    /**
     * 添加产品
     */
    public function productAdd()
    {

        $name = I('name', '', htmlspecialchars());
        $id = I('id', '', htmlspecialchars());

        if (!empty($name)) {
            $where['b.name'] = array('like', "%$name%");
        }

        $page = max(I('get.p'), 1);
        $num = max(I('get.num'), 20);

        $order = "a.store_pid desc";
        $product_relation_model = M('b2c_store_product a');

        $where['a.local_id'] = $this->local_id;
        $where['a.store_status'] = 'true';
        $where['b.disabled'] = 'false';

        $field = "a.marketprice,a.price,a.store,a.discount,a.store_pid,b.product_id,b.goods_id,b.title,b.name,b.spec_info,a.local_id";

        // 可售货品
        $count = $product_relation_model->join(C('DB_PREFIX') . 'b2c_products b on a.product_id=b.product_id')
            ->where($where)
            ->count();

        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $product_relation_msg = $product_relation_model->join(C('DB_PREFIX') . 'b2c_products b on a.product_id=b.product_id', 'left')
            ->where($where)
            ->order($order)
            ->field($field)
            ->page($page, $num)
            ->select();

//        $menu = M('store_carousel')->where(['id' => $id])->find();
//        $value = unserialize($menu['value']);

        $this->assign([
            'product_relation_msg' => $product_relation_msg,
            'show' => $show,
            'id' => $id,
//            'value' => $value
        ]);

        $this->display();
    }



}